#####################################################################
#                                                                   #
#  THIS IS A SOURCE CODE FILE FROM A PROGRAM TO INTERACT WITH THE   #
# LBRY PROTOCOL ( lbry.com ). IT WILL USE THE LBRY SDK ( lbrynet )  #
# FROM THEIR REPOSITORY ( https://github.com/lbryio/lbry-sdk )      #
# WHICH I GONNA PRESENT TO YOU AS A BINARY. SINCE I DID NOT DEVELOP #
# IT AND I'M LAZY TO INTEGRATE IN A MORE SMART WAY. THE SOURCE CODE #
# OF THE SDK IS AVAILABLE IN THE REPOSITORY MENTIONED ABOVE.        #
#                                                                   #
#      ALL THE CODE IN THIS REPOSITORY INCLUDING THIS FILE IS       #
# (C) J.Y.Amihud and Other Contributors 2021. EXCEPT THE LBRY SDK.  #
# YOU CAN USE THIS FILE AND ANY OTHER FILE IN THIS REPOSITORY UNDER #
# THE TERMS OF GNU GENERAL PUBLIC LICENSE VERSION 3 OR ANY LATER    #
# VERSION. TO FIND THE FULL TEXT OF THE LICENSE GO TO THE GNU.ORG   #
# WEBSITE AT ( https://www.gnu.org/licenses/gpl-3.0.html ).         #
#                                                                   #
# THE LBRY SDK IS UNFORTUNATELY UNDER THE MIT LICENSE. IF YOU ARE   #
# NOT INTENDING TO USE MY CODE AND JUST THE SDK. YOU CAN FIND IT ON #
# THEIR OFFICIAL REPOSITORY ABOVE. THEIR LICENSE CHOICE DOES NOT    #
# SPREAD ONTO THIS PROJECT. DON'T GET A FALSE ASSUMPTION THAT SINCE #
# THEY USE A PUSH-OVER LICENSE, I GONNA DO THE SAME. I'M NOT.       #
#                                                                   #
# THE LICENSE CHOSEN FOR THIS PROJECT WILL PROTECT THE 4 ESSENTIAL  #
# FREEDOMS OF THE USER FURTHER, BY NOT ALLOWING ANY WHO TO CHANGE   #
# THE LICENSE AT WILL. SO NO PROPRIETARY SOFTWARE DEVELOPER COULD   #
# TAKE THIS CODE AND MAKE THEIR USER-SUBJUGATING SOFTWARE FROM IT.  #
#                                                                   #
#####################################################################

# This is the seach mechanism

import threading
from flbry import ui
from flbry import fetch
from gi.repository import Gtk
from gi.repository import GLib

def find(win, arg="", channel_ids=[], page=1, r={}, flowbox=False):


    
    #if arg:
    #    c["text"] = arg
    c = {}
    c["text"] = arg
    
    c["channel_ids"] = channel_ids
    c["page"] = page
    
    

    c["order_by"] = "release_time" #{"order_by":"release_time"}
    c["remove_duplicates"] = True
    
    for i in r:
        if r[i]:
            c[i] = r[i]
        elif c[i]:
            del c[i]
    
    channel_load = True
    if len(channel_ids) == 1:
        channel_load = False
    out = fetch.lbrynet("claim_search", c)
    
    same = [win, arg, channel_ids, page+1, r]

    if flowbox:
        def add_to_flowbox(flowbox, out):
            for i in out["items"]:
                flowbox.add(ui.search_item(win, i, channel_load))
            if len(out["items"]) > 1:
                lastthing(win, same, flowbox)
            flowbox.show_all()
        GLib.idle_add(add_to_flowbox, flowbox, out)
    else:
        return [win, out, channel_load, same]

def render(out):

    win, out, channel_load, same = out
    
    scrolled = Gtk.ScrolledWindow()
    scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)

    flowbox = Gtk.FlowBox()
    flowbox.set_valign(Gtk.Align.START)
    flowbox.set_max_children_per_line(30)
    flowbox.set_selection_mode(Gtk.SelectionMode.NONE)



    scrolled.add(flowbox)
    
    box = Gtk.VBox()
    for i in out["items"]:
        flowbox.add(ui.search_item(win, i, channel_load))
    if len(out["items"]) > 1:
        lastthing(win, same, flowbox)
    return scrolled

def lastthing(win, same, flowbox):
    # THis is a hack. I use a spinner to get a draw event
    # when the user scrolls far enough, it will execute it
    # to load more stuff
    spinner_more = ui.icon(win, "loading", "gif")
    flowbox.add(spinner_more)
    def draw_event(w, e):
        
        print("EVENT MOTHERFUCKER")
        w.destroy()
        same.append(flowbox)

        load_thread = threading.Thread(target=find, args=[*same])
        load_thread.setDaemon(True)
        load_thread.start()

    spinner_more.connect("draw", draw_event)
        
    
